package com.es.dao.impl;

import com.es.dao.CCBAccountDao;
import com.es.entity.CCBAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class CCBAccountDaoImpl implements CCBAccountDao {


    @Autowired
    private JdbcTemplate template;

    @Override
    public int createAccount(CCBAccount ccbAccount) {
        String sql = "insert into ccb_account(name,card_no,balance) values (?,?,?)";
        int result = template.update(sql, ccbAccount.getName(),ccbAccount.getCardNo(),ccbAccount.getBalance());
        int i = 10/0;
        return result;
    }

    @Override
    public int withdraw(String cardNo, BigDecimal mount) {
        String sql = "update ccb_account set balance = balance - ? where card_no = ?";

        int i = template.update(sql, mount, cardNo);

        return i;
    }

    @Override
    public int deposit(String cardNo, BigDecimal mount) {
        String sql = "update ccb_account set  balance = balance + ? where card_no = ?";
//        int j = 10/0;
        int i = template.update(sql, mount, cardNo);
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int j = 10/0;
        return i;
    }

    @Override
    public CCBAccount get(Integer id) {
        String sql = "select id,name,card_no,balance from ccb_account where id = ?";
        CCBAccount account = template.queryForObject(sql, new RowMapper<CCBAccount>() {
            @Override
            public CCBAccount mapRow(ResultSet rs, int rowNum) throws SQLException {
                CCBAccount ccbAccount = new CCBAccount();
                ccbAccount.setId(rs.getInt("id"));
                ccbAccount.setName(rs.getString("name"));
                ccbAccount.setCardNo(rs.getString("card_no"));
                ccbAccount.setBalance(rs.getBigDecimal("balance"));
                return ccbAccount;
            }
        }, id);
        return account;
    }
}
